<template>
  <div class="customer-service">
    <h3 class="title">客服设置</h3>

    <!-- 主体表单 -->
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" v-loading="loading">
      <!-- 客服电话 -->
      <el-form-item label="客服电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入客服电话" clearable maxlength="11" />
      </el-form-item>

      <!-- 客服二维码 -->
      <el-form-item label="客服二维码" prop="qrcode">
        <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange"
          accept="image/*" :http-request="handleCustomUpload">
          <!-- 图片预览 -->
          <img v-if="form.qrcode" :src="form.qrcode" class="qrcode-preview">
          <el-button v-else icon="el-icon-upload">选择图片</el-button>

          <!-- 上传提示 -->
          <div slot="tip" class="upload-tip">
            建议尺寸：300x300px，支持 JPG/PNG 格式，大小不超过 2MB
          </div>
        </el-upload>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEditMode ? '保存修改' : '新增客服' }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getService, addOrUpdateService } from '@/api/common'
export default {
  data () {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) return callback(new Error('请输入客服电话'))
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      submitting: false,
      isEditMode: false,
      form: {
        phone: '',
        qrcode: ''
      },
      rules: {
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        // qrcode: [{ required: true, message: '请上传二维码', trigger: 'change' }]
      },
      uploadFile: null // 暂存上传文件
    }
  },

  created () {
    this.fetchCustomerInfo()
  },

  methods: {
    // 获取客服信息
    async fetchCustomerInfo () {
      this.loading = true
      try {
        const res = await getService()
        if (res.data) {
          this.form = res.data
          this.isEditMode = true
        }
      } catch (error) {
        this.$message.error('获取客服信息失败')
      } finally {
        this.loading = false
      }
    },

    // 文件选择回调
    handleFileChange (file) {
      // 校验文件类型和大小
      const isImage = ['image/jpeg', 'image/png'].includes(file.raw.type)
      const isLt2M = file.raw.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
        return false
      }

      // 预览图片
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = () => {
        this.form.qrcode = reader.result
        this.$refs.formRef.validateField('qrcode')
      }

      this.uploadFile = file.raw
      return false // 阻止自动上传
    },

    // 自定义上传
    async handleCustomUpload () {
      if (!this.uploadFile) return

      const formData = new FormData()
      formData.append('file', this.uploadFile)

      try {
        const res = await this.$http.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.code === 200) {
          this.form.qrcode = res.data.url
          this.uploadFile = null
        }
      } catch (error) {
        this.$message.error('图片上传失败')
      }
    },

    // 提交表单
    async handleSubmit () {
      const valid = await this.$refs.formRef.validate()
      if (!valid) return
      // 先上传图片
      // if (this.uploadFile) {
      //   await this.handleCustomUpload()
      // }
      // 提交客服信息
      this.submitting = true
      try {
        if (this.form.id != null) {
          this.isEditMode = true
        }
        addOrUpdateService(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          if (!this.isEditMode) {
            this.isEditMode = true
            this.fetchCustomerInfo()
          }
        });

      } catch (error) {
        this.$message.error('操作失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
.customer-service {
  padding: 20px;
  max-width: 600px;
}

.title {
  margin-bottom: 30px;
  color: #303133;
}

.qrcode-preview {
  width: 200px;
  height: 200px;
  object-fit: contain;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 4px;
}

.upload-tip {
  margin-top: 10px;
  color: #999;
  font-size: 12px;
}
</style>
